package com.tanhua.mongo.api;

import com.tanhua.api.service.VideoApi;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.mongo.utils.IdWorker;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Override
    public String save(Video video) {

        // 设置属性
        video.setVid(idWorker.getNextId("video"));

        // 保存数据
        mongoTemplate.save(video);

        return video.getId().toHexString();
    }

    @Override
    public List<Video> findPageByVid(List<Long> vids) {
        return mongoTemplate.find(Query.query(
                Criteria.where("vid").in(vids)
        ), Video.class);
    }

    @Override
    public List<Video> findPageAll(int page, Integer pagesize) {
        return mongoTemplate.find(new Query()
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")))
        ,Video.class);
    }

    @Override
    public PageResult<Video> findPageVideo(Long uid, Integer page, Integer pagesize) {

        Criteria criteria = Criteria.where("userId").is(uid);

        long count = mongoTemplate.count(new Query(criteria), Video.class);

        Query query = new Query(criteria)
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Video> videoList = mongoTemplate.find(query, Video.class);


        return new PageResult<>(page, pagesize, count, videoList);
    }
}
